package org.argus.job.worker.cloud;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

import org.argus.job.worker.core.ArgusJobWorker;
import org.argus.job.worker.core.common.PowerJobWorkerConfig;
import org.argus.job.worker.core.common.WorkerRuntime;
import org.argus.job.worker.core.extension.processor.ProcessorFactory;
import org.argus.job.common.network.IServiceInstanceIPParser;
import org.argus.job.worker.core.processor.impl.BuildInSpringMethodProcessorFactory;
import org.argus.job.worker.core.processor.impl.BuiltInSpringProcessorFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.google.common.collect.Lists;

/**
 * Spring 项目中的 Worker 启动器
 * 能够获取到由 Spring IOC 容器管理的 processor
 *
 * @author tjq
 * @since 2023/1/20
 */
public class ArgusJobSpringWorker implements ApplicationContextAware, InitializingBean, DisposableBean {

    /**
     * 组合优于继承，持有 ArgusJobWorker，内部重新设置 ProcessorFactory 更优雅
     */
    private ArgusJobWorker argusJobWorker;

    private final IServiceInstanceIPParser workerIPParser;
    private final PowerJobWorkerConfig config;

    public ArgusJobSpringWorker(PowerJobWorkerConfig config, IServiceInstanceIPParser workerIPParser) {
        this.config = config;
        this.workerIPParser = workerIPParser;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        argusJobWorker = new ArgusJobWorker(config, workerIPParser);
        argusJobWorker.init();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BuiltInSpringProcessorFactory springProcessorFactory = new BuiltInSpringProcessorFactory(applicationContext);

        BuildInSpringMethodProcessorFactory springMethodProcessorFactory = new BuildInSpringMethodProcessorFactory(applicationContext);
        // append BuiltInSpringProcessorFactory

        List<ProcessorFactory> processorFactories = Lists.newArrayList(
                Optional.ofNullable(config.getProcessorFactoryList())
                        .orElse(Collections.emptyList()));
        processorFactories.add(springProcessorFactory);
        processorFactories.add(springMethodProcessorFactory);
        config.setProcessorFactoryList(processorFactories);
    }

    @Override
    public void destroy() throws Exception {
        argusJobWorker.destroy();
    }

    public WorkerRuntime getWorkerRuntime() {
        return argusJobWorker.getWorkerRuntime();
    }
}
